package com.ruoyi.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.project.system.entity.SysUser;
import com.ruoyi.project.system.entity.SysUserRole;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysUserRoleService;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.system.vo.SysUserRoleVO;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.mybatis.service.impl.MicaServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户 业务层实现类
 *
 * @author dy
 */
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends MicaServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    private final ISysUserRoleService sysUserRoleService;

    private final SysUserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUserRole(SysUserRoleVO sysUserRoleVO) {
        SysUser sysUser = $.copy(sysUserRoleVO, SysUser.class);
        int result = userMapper.insert(sysUser);
        return result > 0 && submitUserRoles(sysUser.getId(), sysUserRoleVO.getRoleIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserRole(SysUserRoleVO sysUserRoleVO) {
        SysUser sysUser = $.copy(sysUserRoleVO, SysUser.class);
        int result = userMapper.updateById(sysUser);
        return result > 0 && submitUserRoles(sysUser.getId(), sysUserRoleVO.getRoleIds());
    }

    /**
     * 新增用户角色
     */
    public boolean submitUserRoles(Long userId, List<Long> roleIds) {
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
        Set<SysUserRole> sysUserRoles = new HashSet<>();
        if ($.isNotEmpty(roleIds)) {
            roleIds.forEach(v -> {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(v);
                sysUserRoles.add(sysUserRole);
            });
            return sysUserRoleService.saveIgnoreBatch(sysUserRoles);
        }
        return true;
    }
}
